import {CefQueryCfg} from "../message/CefQueryCfg";
import {CefKey} from "../message/CefKey.Const";
import {sendCefQuery} from "../message/cefQueryHandler";
import {Button, Col, Form, FormInstance, Input, Modal, Row, Space, Table, TableProps} from "antd";
import {useAppContext} from "../utils/Context";
import {useState} from "react";
import React from 'react';

export type DataSourceType = {
    id: number;
    name: string;
    path: string;
    sessionId: string;
}
type AddDataSourceFormProps = {
    form: FormInstance,
    dataSources: DataSourceType[],
}

type UploadFileResponseType = {
    fileName: string,
    filePath: string
}
interface UploadFileProps {
    onChange?: (value: string) => void;
}
// todo 最大20
export const DataSource: React.FC = () => {
    const {dataSources, setDataSources, messageApi} = useAppContext();
    // 新增数据源表单是否打开
    const [openModal, setOpenModal] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [form] = Form.useForm<DataSourceType>();
    const columns: TableProps<DataSourceType>['columns'] = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: '30%',
            ellipsis: true
        },
        {
            title: '路径',
            dataIndex: 'path',
            key: 'path',
            width: '50%',
            ellipsis: true
        },
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            render: (_, data) => <Button onClick={() => deleteDataSource(data)}>删除</Button>,
            width: '20%'
        },
    ];
    const addDataSource = async () => {
        setConfirmLoading(true);
        await form.validateFields().then((values) => {
            const cfg = new CefQueryCfg(CefKey.DATASOURCE);
            cfg.data = {
                method: 'add',
                params: values
            }
            sendCefQuery(cfg, (response) => {
                getDataSources((response) => {
                    setDataSources(JSON.parse(response).body as DataSourceType[]);
                });
                setConfirmLoading(false);
                setOpenModal(false);
                form.resetFields();
            });
        }).catch(() => {
            setConfirmLoading(false);
        });
    }

    const deleteDataSource = (data: DataSourceType): void => {
        const cfg = new CefQueryCfg(CefKey.DATASOURCE);
        cfg.data = {
            method: 'delete',
            params: {
                id: data.id
            }
        }
        sendCefQuery(cfg, (response) => {
            getDataSources((response) => {
                setDataSources(JSON.parse(response).body as DataSourceType[]);
            });
        });
    }

    function openAddDatasourceModal() {
        if (dataSources.length > 20) {
            messageApi.warning("数据源数量达到上限(20)，请删除后操作。");
            return;
        }
        setOpenModal(true);
    }

    return (
        <>
            <Row gutter={[undefined, 20]}>
                <Col>
                    <Button onClick={() => openAddDatasourceModal()}>新增</Button>
                        <Modal
                        title="新增数据源"
                        open={openModal}
                        onOk={addDataSource}
                        confirmLoading={confirmLoading}
                        onCancel={() => {
                            setOpenModal(false);
                            form.resetFields();
                        }}
                    >
                        <AddDataSourceForm form={form} dataSources={dataSources}></AddDataSourceForm>
                    </Modal>
                </Col>
                <Col span={24}>
                    <Table columns={columns} dataSource={dataSources} rowKey="id"></Table>
                </Col>
            </Row>
        </>
    );
}

const AddDataSourceForm: React.FC<AddDataSourceFormProps> = (props: AddDataSourceFormProps) => {
    const validateName = (rule: any, value: string) => {
        if (props.dataSources.find(ds => ds.name === value)) {
            return Promise.reject("数据源名称已存在");
        }
        return Promise.resolve();
    }

    return (
        <Form form={props.form}>
            <Form.Item<DataSourceType>
                label="名称"
                name="name"
                rules={[{required: true, message: '输入名称'}, {validator: validateName}]}
            >
                <Input/>
            </Form.Item>
            <Form.Item<DataSourceType>
                label="路径"
                name="path"
                rules={[{required: true, message: '输入路径'}]}
                trigger="onChange"
            >
                <UploadFileComponent></UploadFileComponent>
            </Form.Item>
        </Form>
    );
}

const UploadFileComponent: React.FC<UploadFileProps> = ({onChange}) => {
    const [uploadFileType, setUploadFileType] = useState<UploadFileResponseType>();
    function uploadFile() {
        const cfg = new CefQueryCfg(CefKey.DATASOURCE);
        cfg.data = {
            method: 'upload',
            params: {}
        }
        sendCefQuery(cfg, (response) => {
            const uploadFile: UploadFileResponseType = JSON.parse(response).body;
            setUploadFileType(uploadFile);
            onChange?.(uploadFile.filePath);
        });
    }
    return (
        <Space.Compact style={{width: '100%'}}>
            <Input disabled value={uploadFileType?.fileName}/>
            <Button onClick={uploadFile}>选择文件</Button>
        </Space.Compact>
    );
}
export const getDataSources = (onSuccess: (response: string) => void): void => {
    const cfg = new CefQueryCfg(CefKey.DATASOURCE);
    cfg.data = {
        method: 'get',
        params: {}
    }
    sendCefQuery(cfg, onSuccess);
}